package com.txl.web.servlets;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.txl.domain.UserBean;
import com.txl.domain.UserForm;
import com.txl.exception.UserExistException;
import com.txl.service.UserService;
import com.txl.utils.WebUtils;;
public class RegisterServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		UserForm form = WebUtils.request2Bean(request, UserForm.class);
		//获取图形校验码
		String s_checkcode = (String) request.getSession().getAttribute("checkcode");
		boolean b = form.validate(s_checkcode);
		if(!b){
			request.setAttribute("form", form);
			request.getRequestDispatcher("/jsps/register.jsp").forward(request, response);
			return;
		}
		
		UserBean user = new UserBean();
		WebUtils.copyBean(form, user);
		UserService service = new UserService();
		try {
			service.register(user);
			request.setAttribute("message", "恭喜您，注册成功！浏览器将在3秒后跳转，如果没有跳转，你就点...<meta http-equiv='refresh' content='3;url="+request.getContextPath()+"/jsps/login.jsp'");
			request.getRequestDispatcher("/message.jsp").forward(request, response);
			return;
		} catch (UserExistException e) {
			form.getErrors().put("username", "注册的用户的已存在!!");
			request.setAttribute("form", form);
			request.getRequestDispatcher("/jsps/register.jsp").forward(request, response);
			return;
		} catch(Exception e){
			e.printStackTrace();
			request.setAttribute("message", "服务器出现未知错误！！！");
			request.getRequestDispatcher("/message.jsp").forward(request, response);
			return;
		}
		
	}
		

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

}
